package helper;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android_serialport_api.SerialPort;
import service.Cxd_Service;


/**
 * Created by gw on 2017/5/12.
 */

public class CommandSender {
    private static SerialPort serialPort;
    private static OutputStream os;
    private static InputStream is;
    private static ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static volatile int z;
    private static volatile int y;

    //添加的其他状态
    private static volatile int a;
    private static volatile int b;

    public static void init() {
        try {
            serialPort = new SerialPort(new File("/dev/ttyUSB0"), 115200, 0);
            System.out.println("y======="+y);
            os = serialPort.getOutputStream();
            is = serialPort.getInputStream();
            if (os != null && is != null) {
                queue.startLoop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void destory() {
        if (serialPort != null) {
            serialPort.close();
        }
        if (queue != null) {
            queue.cancelLoop();
            queue.removeAll();
        }
    }

    public static void send(String command) {
        if (queue != null && queue.isLooping()) {
            if (!command.endsWith("\n")) {
                command += "\n";
            }
            queue.add(command);
        }
    }

    public static void send(final File file) {
        if (file.exists()) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(file));
                        String line;
                        while ((line = br.readLine()) != null) {
                            send(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static LoopQueue<String> queue = new LoopQueue<String>(5) {
        @Override
        public void loop(String object) {
            try {
                object = object.toLowerCase();
                if (object.startsWith("g1")) {
                    //添加的其他状态
                    int da = 0;
                    int db = 0;

                    int dz = 0;
                    int dy = 0;
                    //添加的其他状态--a,b
                    int ta = a;
                    int tb = b;

                    int tz = z;
                    int ty = y;
                    if (object.contains("z")) {
//                        tx = Integer.parseInt(object.substring(object.indexOf("x")+1, object.indexOf(" ", object.indexOf("x"))));
                        tz = Integer.parseInt(normalize_word(object, object.indexOf("z")));
                        dz = tz - z;
                    }
                    if (object.contains("y")) {
//                        ty = Integer.parseInt(object.substring(object.indexOf("y")+1, object.indexOf("\n", object.indexOf("y"))));
                        ty = Integer.parseInt(normalize_word(object, object.indexOf("y")));
                        dy = ty - y;
                    }
                    //其他状态a,b
                    if (object.contains("a")) {
//                        ty = Integer.parseInt(object.substring(object.indexOf("y")+1, object.indexOf("\n", object.indexOf("y"))));
                        ta = Integer.parseInt(normalize_word(object, object.indexOf("a")));
                        da = ta - a;
                    }
                    if (object.contains("b")) {
//                        ty = Integer.parseInt(object.substring(object.indexOf("y")+1, object.indexOf("\n", object.indexOf("y"))));
                        tb = Integer.parseInt(normalize_word(object, object.indexOf("b")));
                        db = tb - b;
                    }
/*
//---------------------------------------------延迟的命令

                    while (z != tz || y != ty ||a !=ta||b !=tb) {
                        if (z != tz) {s
                            if (dz > 0) {
                                z = z + 1;
                            } else if (dz < 0) {
                                z = z - 1;
                            }
//                            x += dx>0 ? 1 : -1;
                        }
                        if (y != ty) {
                            if (dy > 0) {
                                y = y + 1;
                            } else if (dy < 0) {
                                y = y - 1;
                            }
//                            y += dy>0 ? 1 : -1;
                        }
                        //其他的命令a,b
                        if (a != ta) {
                            if (da > 0) {
                                a = a + 1;
                            } else if (dy < 0) {
                                a = a - 1;
                            }
//                            y += dy>0 ? 1 : -1;
                        }
                        if (b != tb) {
                            if (db > 0) {
                                b = b + 1;
                            } else if (dy < 0) {
                                b = b - 1;
                            }
//                            y += dy>0 ? 1 : -1;
                        }

                        os.write(("G1 Z" + z + " Y" + y +" A"+ a +" B"+ b + "\n").getBytes());
                        System.out.println("G1 X" + z + " Y" + y + "\n");
                        Thread.sleep(30);
                    }
//---------------------------------------------延迟的命令
*/


                    //直接发送命令：

                    os.write(("G1 Z" + tz + " Y" + ty +" A"+ ta +" B"+ tb + "\n").getBytes());
                    os.flush();
                    System.out.println("G1 Z" + tz + " Y" + ty +" A"+ ta +" B"+ tb + "\n");
      //-------------------------------------------
                } else {
                    os.write(object.getBytes());
                    os.flush();
                   // System.out.println("T相关的命令===================="+object.getBytes());
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                baos.write(buffer, 0, is.read(buffer));
                baos.flush();

                byte[] bytes = baos.toByteArray();
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] == 0xff || bytes[i] == -1) {
                        Cxd_Service.getInstance().getHardwareManager().setTemp(bytes[i + 1] * 256 + bytes[i + 2]);
                        Cxd_Service.getInstance().getHardwareManager().setHumi(bytes[i + 3] * 256 + bytes[i + 4]);
                        break;
                    }
                }
                for (int i = 0; i < bytes.length - 1; i++) {
                    if (bytes[i] == 0x42 || bytes[i + 1] == 0x4d) {
                        Cxd_Service.getInstance().getHardwareManager().setPm10(bytes[i + 4] * 256 + bytes[i + 5]);
                        Cxd_Service.getInstance().getHardwareManager().setPm25(bytes[i + 6] * 256 + bytes[i + 7]);
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                this.cancelLoop();
                init();
            }
        }
    };

    public static String normalize_word(String str, int start) {
        str = str.substring(start + 1);
        StringBuilder builder = new StringBuilder();
        if (str.startsWith("+") || str.startsWith("-")) {
            builder.append(str.charAt(0));
            str = str.substring(1);
        }
        int size = str.length();
        int i;
        for (i = 0; i < size; i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                builder.append(ch);
            } else {
                break;
            }
        }
        str = str.substring(i);
        size = str.length();
        if (str.startsWith(".")) {
            builder.append(str.charAt(0));
            str = str.substring(1);
            size = str.length();
            for (i = 0; i < size; i++) {
                char ch = str.charAt(i);
                if (Character.isDigit(ch)) {
                    builder.append(ch);
                } else {
                    break;
                }
            }
        }
        return builder.toString();
    }
}
